package com.uduemc.biso.node.web.service.impl;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.uduemc.biso.core.common.extities.ctemplatelistdata.CTemplateItemData;
import com.uduemc.biso.core.extities.center.Host;
import com.uduemc.biso.node.core.common.entities.ThemeObject;
import com.uduemc.biso.node.core.common.entities.srhtml.SRHead;
import com.uduemc.biso.node.core.common.entities.themeobject.ThemeObjectSource;
import com.uduemc.biso.node.core.entities.HDomain;
import com.uduemc.biso.node.core.entities.SConfig;
import com.uduemc.biso.node.core.entities.custom.SSeoSiteSnsConfig;
import com.uduemc.biso.node.core.property.GlobalProperties;
import com.uduemc.biso.node.core.utils.SitePathUtil;
import com.uduemc.biso.node.web.component.RequestHolder;
import com.uduemc.biso.node.web.entities.AccessHost;
import com.uduemc.biso.node.web.exception.NotFound404Exception;
import com.uduemc.biso.node.web.service.SRHeadSearchPageService;
import com.uduemc.biso.node.web.service.SRHeadService;
import com.uduemc.biso.node.web.service.SeoCodeService;
import com.uduemc.biso.node.web.service.ThemeService;
import com.uduemc.biso.node.web.service.byfeign.TemplateService;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;

@Service
public class SRHeadSearchPageServiceImpl implements SRHeadSearchPageService {

	@Autowired
	private RequestHolder requestHolder;

	@Autowired
	private ThemeService themeServiceImpl;

	@Autowired
	private SRHeadService sRHeadServiceImpl;

	@Autowired
	private SeoCodeService seoCodeServiceImpl;

	@Autowired
	private GlobalProperties globalProperties;

	@Autowired
	private TemplateService templateServiceImpl;

	@Override
	public void makeSRHead(SRHead srHead) throws JsonParseException, JsonMappingException, JsonProcessingException, IOException, NotFound404Exception {
		String theme = requestHolder.getAccessSite().getSiteConfig().getTheme();
		ThemeObject themeObject = themeServiceImpl.getThemeObject(theme);

		List<ThemeObjectSource> head = themeObject.getHead();
		if (CollUtil.isEmpty(head)) {
			return;
		}

		StringBuilder themeMeta = new StringBuilder();
		StringBuilder title = new StringBuilder();
		StringBuilder dynamicMeta = new StringBuilder();
		StringBuilder sourceInclude = new StringBuilder();
		StringBuilder sourceComponentsjsSource = new StringBuilder();
		StringBuilder sourceThemeSource = new StringBuilder();
		StringBuilder sourceCustomContent = new StringBuilder();
		StringBuilder sourceSourceTags = new StringBuilder();

		for (ThemeObjectSource themeObjectSource : head) {
			String author = themeObjectSource.getAuthor();
			if (!ArrayUtil.<String>contains(SRHeadServiceImpl.AUTHOR, author)) {
				continue;
			}
			String type = themeObjectSource.getType();
			if (type.equals("<ThemeMeta>")) {
				themeMeta.append(sRHeadServiceImpl.makeThemeMeta());
			} else if (type.equals("<Title>")) {
				title.append(title());
			} else if (type.equals("<DynamicMeta>")) {
				dynamicMeta.append(meta());
			} else if (type.equals("<ComponentsjsSource>")) {
				sourceComponentsjsSource.append(sRHeadServiceImpl.makeComponentsjsSource());
			} else if (type.equals("<ThemeSource>")) {
				sourceThemeSource.append(sRHeadServiceImpl.makeThemeSource());
			} else if (type.equals("<CustomContent>")) {
				sourceCustomContent.append("\n" + themeObjectSource.getContent());
			} else if (type.equals("<SourceTags>")) {
				sourceSourceTags.append(sRHeadServiceImpl.makeSourceTags(themeObjectSource.getSource()));
			} else if (StrUtil.startWith(type, "<Include:")) {
				sourceInclude.append(sRHeadServiceImpl.makeInclude(type));
			}
		}

		// favicon.ico 放入动态的
		StringBuilder favicon = sRHeadServiceImpl.favicon();

		StringBuilder dynamicSource = new StringBuilder("\n<!-- dynamicSource -->");

		// 插件部分 plugins
		StringBuilder plugins = sRHeadServiceImpl.plugins();

		StringBuilder endHead = endHead();

		srHead.setTitle(title).setTmeta(themeMeta).setMeta(dynamicMeta).setFavicon(favicon).setSourceInclude(sourceInclude)
				.setSourceComponentsjsSource(sourceComponentsjsSource).setSourceThemeSource(sourceThemeSource).setSourceCustomContent(sourceCustomContent)
				.setSourceComponentsjsSource(sourceComponentsjsSource).setPlugins(plugins).setDynamicSource(dynamicSource).setEndHead(endHead);
	}

	@Override
	public StringBuilder title() {
		StringBuilder title = new StringBuilder();
		try {
			String searchPageTitle = seoCodeServiceImpl.searchPageTitle();
			title.append("\n<title>" + searchPageTitle + "</title>");
			title.append("\n<meta name=\"apple-mobile-web-app-title\" content=\"" + searchPageTitle + "\">");
			title.append("\n<meta name=\"apple-mobile-web-app-capable\" content=\"yes\"/>");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return title;
	}

	@Override
	public StringBuilder meta() throws JsonParseException, JsonMappingException, IOException {
		StringBuilder meta = new StringBuilder();
		String keywords = seoCodeServiceImpl.searchPageKeywords();
		String description = seoCodeServiceImpl.searchPageDescription();
		String author = seoCodeServiceImpl.author();
		String revisitAfter = seoCodeServiceImpl.revisitAfter();
		List<SSeoSiteSnsConfig> snsConfig = seoCodeServiceImpl.snsConfig();

		// md5 对 biso+[域名] 进行加密
		String biso = SecureUtil.md5("biso" + requestHolder.getRequest().getServerName());

		meta.append("\n<meta name=\"keywords\" content=\"" + keywords + "\" />");
		meta.append("\n<meta name=\"description\" content=\"" + description + "\" />");
		meta.append("\n<meta name=\"author\" content=\"" + author + "\" />");
		meta.append("\n<meta name=\"revisit-after\" content=\"" + revisitAfter + "\" />");

		if (CollUtil.isNotEmpty(snsConfig)) {
			for (SSeoSiteSnsConfig sSeoSiteSnsConfig : snsConfig) {
				String property = sSeoSiteSnsConfig.getProperty();
				String content = sSeoSiteSnsConfig.getContent();
				meta.append("\n<meta property=\"" + property + "\" content=\"" + content + "\" />");
			}
		}

		meta.append("\n<meta name=\"renderer\" content=\"webkit\" />");
//		meta.append("\n<!-- 不让百度转码 -->");
		meta.append("\n<meta http-equiv=\"Cache-Control\" content=\"no-siteapp\" />");
//		meta.append("\n<!-- uc强制竖屏 -->");
		meta.append("\n<meta name=\"screen-orientation\" content=\"portrait\" />");
//		meta.append("\n<!-- QQ强制竖屏 -->");
		meta.append("\n<meta name=\"x5-orientation\" content=\"portrait\" />");
//		meta.append("\n<!-- UC强制全屏 -->");
		meta.append("\n<meta name=\"full-screen\" content=\"yes\" />");
//		meta.append("\n<!-- QQ强制全屏 -->");
		meta.append("\n<meta name=\"x5-fullscreen\" content=\"true\" />");
//		meta.append("\n<!-- UC应用模式 -->");
		meta.append("\n<meta name=\"browsermode\" content=\"application\" />");
//		meta.append("\n<!-- QQ应用模式 -->");
		meta.append("\n<meta name=\"x5-page-mode\" content=\"app\" />");
		meta.append("\n<meta name=\"ibiso\" content=\"" + biso + "\" />");
		String afterMeta = seoCodeServiceImpl.searchPageAfterMeta();
		meta.append(afterMeta);

		HDomain hDomain = requestHolder.getAccessHost().getHDomain();
		if (hDomain != null && hDomain.getDomainType().shortValue() == (short) 0) {
			Host host = requestHolder.getAccessHost().getHost();
			meta.append("\n<meta name=\"site-token\" content=\"" + host.getRandomCode() + "-" + SecureUtil.sha1(host.getRandomCode()) + "\" />");
		}

		// 模板编号，颜色编号
		String color = "(-1)";
		String theme = "(-1)";
		String templateName = "(-1)";
		if (requestHolder != null && requestHolder.getAccessSite() != null && requestHolder.getAccessSite().getSiteConfig() != null) {
			SConfig siteConfig = requestHolder.getAccessSite().getSiteConfig();
			color = siteConfig.getColor();
			theme = siteConfig.getTheme();
			CTemplateItemData cTemplateItemData = templateServiceImpl.getCTemplateItemData(requestHolder.getAccessSite().getSiteConfig().getTemplateId());
			if (cTemplateItemData != null) {
				templateName = cTemplateItemData.getTemplateName();
			} else {
				cTemplateItemData = templateServiceImpl.getCTemplateItemDataByUrl(requestHolder.getAccessHost().getHDomain());
				if (cTemplateItemData != null) {
					templateName = cTemplateItemData.getTemplateName();
				}
			}
		}
		meta.append("\n<meta name=\"Template-Theme-Color\" content=\"" + templateName + "-" + theme + "-" + color + "\" />");

		String basePath = globalProperties.getSite().getBasePath();
		String userPathByCode = SitePathUtil.getUserPathByCode(basePath, requestHolder.getHost().getRandomCode());
		String hostPath = StrUtil.replace(userPathByCode, basePath, "");
		meta.append("\n<meta name=\"Host-Path\" content=\"" + hostPath + "\" />");
		AccessHost accessHost = requestHolder.getAccessHost();
		if (accessHost.getHost().getEndAt() != null) {
			meta.append("\n<meta name=\"End-At\" content=\"" + (new SimpleDateFormat("yyyy-MM-dd")).format(accessHost.getHost().getEndAt()) + "\" />");
		}

		return meta;
	}

	@Override
	public StringBuilder endHead() {
		StringBuilder endHead = new StringBuilder();
		String beforeEndHead = seoCodeServiceImpl.searchPageBeforeEndHead();
		endHead.append(beforeEndHead);
		return endHead;
	}

}
